//
//  YLAListViewController.swift
//  Your Lover AI
//
//  Created by 阿忠 on 2024/6/18.
//

import Foundation
import UIKit
import SnapKit
import Alamofire
import CryptoKit
import SCrypto
import SwiftyJSON
import SDWebImage
import SVProgressHUD


class YLAListViewController: UIViewController, UITableViewDataSource,UITableViewDelegate{
    
    var title_lb: UILabel!      // 标题
    var tableView : UITableView!
    private var listData = "YLAChatCell"
    var NowComm_date = NSArray()
    var Role_date: [[String: String]] = []
    var homeList_date = NSArray()
    
    lazy var bgImg: UIImageView = {
        let image = UIImageView(image: UIImage(named: "bg"))
        return image
    }()
    
    
    lazy var nochatImg: UIImageView = {
        let image = UIImageView(image: UIImage(named: "img_nochat"))
        return image
    }()
    
    lazy var nochatLab: UILabel = {
        let lab = UILabel()
        lab.textColor = .white
        lab.font = UIFont.boldSystemFont(ofSize: 15)
        lab.textAlignment = .center
        lab.text = "No chat"
        return lab
    }()
    
    
    override func viewDidLoad() {
        super.viewDidLoad()

        self.view.backgroundColor = UIColor.red
 
        setUI()
        setRequest()
   
        
    }
    
    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        self.tabBarController!.tabBar.isHidden = false
        storageRoleId()
    }
    
    func storageRoleId(){
        // 从UserDefaults中检索是否有机器人信息
        if let retrievedData = UserDefaults.standard.data(forKey: "RoleidList"),
            var RoleidList = try? PropertyListDecoder().decode([[String: String]].self, from: retrievedData) {

            self.Role_date = RoleidList
            print(RoleidList)
            if self.Role_date.count > 0 {
                nochatImg.isHidden = true
                nochatLab.isHidden = true
            }
            self.tableView.reloadData()

        } else {
            print("没有")
        }
    }
    
    func setUI() {
        
        view.addSubview(bgImg)
        bgImg.snp.makeConstraints { make in
            make.left.top.bottom.right.equalToSuperview()
        }
        
        title_lb = UILabel()
        title_lb.textColor = .white
        title_lb.font = UIFont.boldSystemFont(ofSize: 25)
        title_lb.textAlignment = .left
        title_lb.text = "Chat"
        view.addSubview(title_lb)
        title_lb.snp.makeConstraints { make in
            make.left.equalTo(17)
            make.top.equalTo(55)
            make.height.equalTo(25)
        }
        
        tableView = UITableView()
        tableView.backgroundColor = .clear
        tableView.separatorStyle = .none
        view.addSubview(tableView)
        tableView.snp.makeConstraints { make in
            make.left.right.equalToSuperview()
            make.top.equalTo(title_lb.snp.bottom).offset(20)
            make.bottom.equalTo(-55)
        }
        view.addSubview(tableView)
        tableView.dataSource = self
        tableView.delegate = self
        extendedLayoutIncludesOpaqueBars = true;
        if #available(iOS 11.0, *) {
            tableView.contentInsetAdjustmentBehavior = .never
        } else {
            automaticallyAdjustsScrollViewInsets = false;
        };
        
        tableView.reloadData()
        
        view.addSubview(nochatImg)
        nochatImg.snp.makeConstraints { make in
            make.centerX.equalToSuperview()
            make.top.equalTo(260)
            make.width.equalTo(260)
            make.height.equalTo(140)
        }
        
        view.addSubview(nochatLab)
        nochatLab.snp.makeConstraints { make in
            make.centerX.equalToSuperview()
            make.top.equalTo(nochatImg.snp.bottom).offset(32)
        }
        
      
        
    }
    
    func setRequest() {
        
        let dataStr: String!
        
        let uuid = UUID().uuidString
        let userInfo: [String: Any] = [
            "userId": uuid,
            "userType": "1",
            "deviceType": "1"
        ]
        
        do {
            // 使用JSONSerialization将字典转换为Data
            let jsonData = try JSONSerialization.data(withJSONObject: userInfo, options: [])
            
            // jsonData已经是UTF-8编码的，因为JSONSerialization默认使用UTF-8
            // 如果你需要再次确认其是UTF-8编码，你可以这样做（但实际上不是必须的）
            if let utf8Data = String(data: jsonData, encoding: .utf8)?.data(using: .utf8) {
                // utf8Data 现在包含与 jsonData 相同的UTF-8编码的Data
                // 但这一步是多余的，因为 jsonData 已经是UTF-8了
            }

            print(jsonData)
//            let plaintext = "plain text".data(using: String.Encoding.utf8)!
            let sharedSecretKey = "= cpfD4i3rkTA/xJMwOoFYrQ==".data(using: String.Encoding.utf8)!.SHA256() // AES-256
            let IV = try! Data.random(16) // Randomly generated IV. Length is equal to the AES block size(128)
            let ciphertext = try! jsonData.encrypt(.aes, options: .PKCS7Padding, key: sharedSecretKey, iv: IV)
            
            dataStr = dataToHexString(ciphertext)
            print(dataStr)
            
        } catch {
            // 处理JSON序列化过程中的任何错误
            print("Failed to serialize userInfo to JSON")
            return
        }

        
        
        let headers: HTTPHeaders = [
            "accept-encoding" : "gzip",
            "connection" : "Keep-Alive",
            "content-length" : "45",
            "Content-Type": "application/json",
            "data" :dataStr,
            "user-agent": "okhttp/4.10.0"
        ]
        
        let timestampMilliseconds = getCurrentTimestampMilliseconds()
        let parameters: [String: Any] = [
            "productId": "2",
            "timestamp": timestampMilliseconds
        ]
        SVProgressHUD.show()
//        Alamofire.request(YLARequest().robotListUrl, method: .post, parameters: parameters,encoding: JSONEncoding.default,headers: headers).responseJSON { response in
//            switch response.result {
//            case .success(let value):
//                SVProgressHUD.dismiss()
//                let json = JSON.init(value)
//                if json["code"].intValue != 200 {
//                            print(json["message"].stringValue)
//                            return
//                        }
//                let tipcode = json["code"]
//                if let json = value as? [String: Any]{
//                    let tipCpde = json["code"] as? Int
//                    if tipCpde == 200 {//成功
//                        self.homeList_date = json["data"] as! NSArray
//  
//                        print(self.homeList_date)
//                        } else {
//                            let msgStr = json["msg"] as? String
//                           
//                          
//                        }
//                   
//                                        
//                } else {
//                    SVProgressHUD.dismiss()
//                    print("Invalid JSON format or missing 'data' field")
//                }
//            case .failure(let error):
//                // 请求失败，处理错误信息
//                print("Error: \(error)")
//                SVProgressHUD.dismiss()
//            }
//        }
    }
    
    
    //MARK: UITableViewDataSource
    // cell的个数
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return self.Role_date.count
    }
    // UITableViewCell
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let dict:Dictionary = self.Role_date[indexPath.row]
        let cellid = "testCellID"
        var cell:YLAChatCell? = tableView.dequeueReusableCell(withIdentifier: cellid) as? YLAChatCell
        if cell==nil {
            cell = YLAChatCell(style:.subtitle, reuseIdentifier: cellid)
            
        }
        cell?.nameLab.text = dict["name"]
        cell?.timeLab.text = dict["time"]
        cell?.contentLab.text = dict["msgContent"]
        cell?.iconImg.sd_setImage(with: URL(string: dict["coverUrl"]!), placeholderImage: UIImage(named: "logo"))
        cell?.backgroundColor = .clear
        cell?.selectionStyle = .none
        
        return cell!
    }
    
    //MARK: UITableViewDelegate
    // 设置cell高度
    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        return 95
    }
    func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
        return 20
    }
    // 选中cell后执行此方法
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        
      print("------选中了chat的cell------")
        let dict:Dictionary = self.Role_date[indexPath.row]
        let roleID = dict["roleIdind"]
        var number = Int(roleID!)
        number! -= 1
        let listData = self.homeList_date[number!]
        
        if roleID == "1" {
            let talkVc = YLATalkViewController()
            let jsonObj = JSON.init(listData)
            let roleId = jsonObj["roleId"].stringValue
            let roleName = jsonObj["name"].stringValue
            let roleCoverUrl = jsonObj["coverUrl"].stringValue
            talkVc.roleId = roleId
            talkVc.roleName = roleName
            talkVc.roleCoverUrl = roleCoverUrl
            self.navigationController?.pushViewController(talkVc, animated: true)
        }else if roleID == "2" {
            let talkVc = YLATalk2ViewController()
            let jsonObj = JSON.init(listData)
            let roleId = jsonObj["roleId"].stringValue
            let roleName = jsonObj["name"].stringValue
            let roleCoverUrl = jsonObj["coverUrl"].stringValue
            talkVc.roleId = roleId
            talkVc.roleName = roleName
            talkVc.roleCoverUrl = roleCoverUrl
            self.navigationController?.pushViewController(talkVc, animated: true)
        }else if roleID == "3" {
            let talkVc = YLATalk3ViewController()
            let jsonObj = JSON.init(listData)
            let roleId = jsonObj["roleId"].stringValue
            let roleName = jsonObj["name"].stringValue
            let roleCoverUrl = jsonObj["coverUrl"].stringValue
            talkVc.roleId = roleId
            talkVc.roleName = roleName
            talkVc.roleCoverUrl = roleCoverUrl
            self.navigationController?.pushViewController(talkVc, animated: true)
        }else if roleID == "4" {
            let talkVc = YLATalk4ViewController()
            let jsonObj = JSON.init(listData)
            let roleId = jsonObj["roleId"].stringValue
            let roleName = jsonObj["name"].stringValue
            let roleCoverUrl = jsonObj["coverUrl"].stringValue
            talkVc.roleId = roleId
            talkVc.roleName = roleName
            talkVc.roleCoverUrl = roleCoverUrl
            self.navigationController?.pushViewController(talkVc, animated: true)
        }else if roleID == "5" {
            let talkVc = YLATalk5ViewController()
            let jsonObj = JSON.init(listData)
            let roleId = jsonObj["roleId"].stringValue
            let roleName = jsonObj["name"].stringValue
            let roleCoverUrl = jsonObj["coverUrl"].stringValue
            talkVc.roleId = roleId
            talkVc.roleName = roleName
            talkVc.roleCoverUrl = roleCoverUrl
            self.navigationController?.pushViewController(talkVc, animated: true)
        }else if roleID == "6" {
            let talkVc = YLATalk6ViewController()
            let jsonObj = JSON.init(listData)
            let roleId = jsonObj["roleId"].stringValue
            let roleName = jsonObj["name"].stringValue
            let roleCoverUrl = jsonObj["coverUrl"].stringValue
            talkVc.roleId = roleId
            talkVc.roleName = roleName
            talkVc.roleCoverUrl = roleCoverUrl
            self.navigationController?.pushViewController(talkVc, animated: true)
        }else{
            let talkVc = YLATalk7ViewController()
            let jsonObj = JSON.init(listData)
            let roleId = jsonObj["roleId"].stringValue
            let roleName = jsonObj["name"].stringValue
            let roleCoverUrl = jsonObj["coverUrl"].stringValue
            talkVc.roleId = roleId
            talkVc.roleName = roleName
            talkVc.roleCoverUrl = roleCoverUrl
            self.navigationController?.pushViewController(talkVc, animated: true)
        }
       
        
    }
    
    func getCurrentTimestampMilliseconds() -> Int64 {
        let date = Date()
        let timeInterval = date.timeIntervalSince1970
        return Int64(timeInterval * 1000)
    }
    
    func encrypt(text: String, key: SymmetricKey) -> Data {
        let data = text.data(using: .utf8)!
        let sealedBox = try! AES.GCM.seal(data, using: key)
        return sealedBox.combined!
    }
    
    func dataToHexString(_ data: Data) -> String {
        let hexChars = "0123456789ABCDEF"
        var hexString = ""
        
        for byte in data {
            hexString += String(format: "%02x", byte)
        }
        
        return hexString
    }
    
}
